//
//  SNProductionPlanningCell.m
//  ZhuoxinAgriculture
//
//  Created by stone on 16/12/23.
//  Copyright © 2016年 stone. All rights reserved.
//
#define RGBColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1]

#define RGBAColor(r, g, b ,a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:a]

#define RandColor RGBColor(arc4random_uniform(255), arc4random_uniform(255), arc4random_uniform(255))

#import "UIImageView+WebCache.h"
#import "SNProductionPlanningCell.h"
#import "Masonry.h"
//=****** add class ****************** stone ***
@interface SNPlanNumberModel : NSObject
/** numberString */
@property (nonatomic,copy) NSString * numberString;
/** nameString */
@property (nonatomic,copy) NSString * nameString;
/** bgcolor */
@property (nonatomic,strong) UIColor * color;
@end

@implementation SNPlanNumberModel



@end
//=************************ stone ***
@interface SNProductionPlanningCell()
/** imageView */
@property (weak, nonatomic) UIView * bgView;

@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *numberLabels;

/** labels */
@property (nonatomic,strong) NSMutableArray<UILabel *> * labels;
/** bottomLabels */
@property (nonatomic,strong) NSMutableArray<UILabel *> * bottomLabels;

@property (weak, nonatomic) IBOutlet UILabel *typenameLabel;
@property (weak, nonatomic) IBOutlet UILabel *usernameLabel;
@property (weak, nonatomic) IBOutlet UILabel *userphoneLabel;
@property (weak, nonatomic) IBOutlet UIImageView *iconImageView;

@end
@implementation SNProductionPlanningCell
-(void)setModel:(SNPlantingDecisionMakerResult *)model{
    _model = model;
    
    [self addViews:model];
    [self setupUI];
    
    //    dispatch_async(dispatch_get_main_queue(), ^{
    
    for(int i = 0; i < self.labels.count; i++) {
        UILabel * label = self.labels[i];
        
        if (i==0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                label.layer.masksToBounds = YES;
                
                CAShapeLayer *maskLayer = [CAShapeLayer layer];
                maskLayer.path = [UIBezierPath bezierPathWithRoundedRect:label.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerTopLeft | UIRectCornerBottomRight | UIRectCornerTopRight cornerRadii: CGSizeMake(3.0f, 3.0f)].CGPath;
                
                label.layer.mask = maskLayer;
            });
            
            
            //                label.layer.cornerRadius = 4;
            //                label.layer.masksToBounds = YES;
            
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                label.layer.masksToBounds = YES;
                
                CAShapeLayer *maskLayer = [CAShapeLayer layer];
                maskLayer.path = [UIBezierPath bezierPathWithRoundedRect:label.bounds byRoundingCorners: UIRectCornerBottomLeft | UIRectCornerTopLeft | UIRectCornerBottomRight | UIRectCornerTopRight  cornerRadii: CGSizeMake(3.0f, 3.0f)].CGPath;
                
                label.layer.mask = maskLayer;
            });
            
        }
    }
    
    //    });
}
/** labels 懒加载 */
- (NSMutableArray<UILabel *> *)labels {
    if (_labels == nil) {
        _labels = [NSMutableArray array];
    }
    return _labels;
}
/** bottomLabels 懒加载 */
- (NSMutableArray<UILabel *> *)bottomLabels {
    if (_bottomLabels == nil) {
        _bottomLabels = [NSMutableArray array];
    }
    return _bottomLabels;
}
//===================================== stone ===========/
- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        self.contentView.backgroundColor = HexRGB(0xf5f5f5);
    }
    return self;
}
- (void)addViews:(SNPlantingDecisionMakerResult *)model
{
    [self.labels enumerateObjectsUsingBlock:^(UILabel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        [obj removeFromSuperview];
    }];
    
    [self.bottomLabels enumerateObjectsUsingBlock:^(UILabel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        [obj removeFromSuperview];
    }];
    
    [self.bgView removeFromSuperview];
    
    //sn_note:=========  ============================ stone 🐳 ===========/
    NSLog(@"%@",model.photo);
    //    model.photo = @"http://zhuoxin.zxdev.cn//api/v1/base/attach/3852314630097600512/down/";
    if (model.photo.length > 0) {
        NSString * urlString = [model.photo stringByReplacingOccurrencesOfString:@"//" withString:@"/"];
        urlString = [urlString stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
        
        NSFileManager * manager = [NSFileManager defaultManager];
        NSString * filename = [SNUtils cachedFileNameForKey:urlString];
        if ([manager fileExistsAtPath:kCachePath(filename)]) {
            [self.iconImageView sd_setImageWithURL:[NSURL fileURLWithPath:kCachePath(filename)] placeholderImage:kUserIconDefaultImage];
        }else{
            [[ZXHTTPManager sharedManager] GET:urlString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSData *  _Nullable responseObject) {
                
                NSString * filename = [SNUtils cachedFileNameForKey:urlString];
                
                [responseObject writeToFile:kCachePath(filename) atomically:YES];
                
                // UIImage * image = [UIImage imageWithData:responseObject];
                NSLog(@"kCachePath(filename) = %@",kCachePath(filename));
                [self.iconImageView sd_setImageWithURL:[NSURL fileURLWithPath:kCachePath(filename)] placeholderImage:kUserIconDefaultImage];
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                NSLog(@"%@",error);
            }];
        }
    }else{
        [self.iconImageView sd_setImageWithURL:[NSURL URLWithString:model.photo] placeholderImage:kUserIconDefaultImage];
    }
    //sn_note:=========  ============================ stone 🐳 ===========/
    //    [self.iconImageView sd_setImageWithURL:[NSURL fileURLWithPath:@"/Users/stone/Pictures/sucai/image01.jpg"] placeholderImage:kUserIconDefaultImage];
    
    //    [self.iconImageView sd_setImageWithURL:[NSURL URLWithString:model.photo] placeholderImage:kUserIconDefaultImage];
    
    self.usernameLabel.text = model.custName;
    
    self.typenameLabel.text = model.fullName;
    
    self.userphoneLabel.text = [NSString stringWithFormat:@"电话: %@",model.phone];
    
    NSMutableArray<SNPlanNumberModel *> * planNumberModels = @[].mutableCopy;
    
    if(model.draft.length>0 && ![model.draft isEqualToString:@"0"]){
        SNPlanNumberModel * mm = [SNPlanNumberModel new];
        mm.nameString = @"待提交";
        mm.numberString = model.draft;
        mm.color = HexRGB(0x6A686F);
        [planNumberModels addObject:mm];
    }
    if(model.approval.length>0 && ![model.approval isEqualToString:@"0"]){
        SNPlanNumberModel * mm = [SNPlanNumberModel new];
        mm.nameString = @"待审核";
        mm.numberString = model.approval;
        mm.color = HexRGB(0xF49E24);
        [planNumberModels addObject:mm];
        
    }
    if(model.passed.length>0 && ![model.passed isEqualToString:@"0"]){
        SNPlanNumberModel * mm = [SNPlanNumberModel new];
        mm.nameString = @"已通过";
        mm.numberString = model.passed;
        mm.color = HexRGB(0x47CA2F);
        [planNumberModels addObject:mm];
    }
    //    if(model.repealed.length>0 || ![model.repealed isEqualToString:@"0"]){
    //        SNPlanNumberModel * mm = [SNPlanNumberModel new];
    //        mm.nameString = @"已废除";
    //        mm.numberString = model.repealed;
    //        [planNumberModels addObject:mm];
    //    }
    for(int i = 0; i < planNumberModels.count; i++) {
        
        UILabel * titleLabel = ({
            UILabel * label = [[UILabel alloc] init];
            /** GPU 优化 */
            //            label.opaque = YES;
            label.backgroundColor = planNumberModels[i].color;
            //            label.layer.masksToBounds = YES;
            //------------------------------
            label.numberOfLines = 0;
            label.textColor = [UIColor whiteColor];
            label.textAlignment = NSTextAlignmentCenter;
            label.text = [NSString stringWithFormat:@"%@个",planNumberModels[i].numberString];
            label.font = [UIFont systemFontOfSize:11];
            
            // [self addSubview:label];
            // [self.view addSubview:label];
            [self.contentView insertSubview:label atIndex:0];
            
            [label mas_makeConstraints:^(MASConstraintMaker * make) {
                make.left.mas_equalTo(self.typenameLabel.mas_left).offset(i*(45-4));
                //                make.right.mas_equalTo(self.contentView.mas_right).offset(0);
                make.top.mas_equalTo(self.typenameLabel.mas_bottom).offset(10);
                //                make.bottom.mas_equalTo(self.contentView.mas_bottom).offset(0);
                
                make.width.mas_equalTo(45);
                make.height.mas_equalTo(15);
            }];
            
            label;
        });
        
        UILabel * bottomLabel = ({
            UILabel * label = [[UILabel alloc] init];
            /** GPU 优化 */
            //            label.opaque = YES;
            //            label.backgroundColor = [UIColor whiteColor];
            //            label.layer.masksToBounds = YES;
            //------------------------------
            label.numberOfLines = 0;
            label.textColor = HexRGB(0x818181);
            label.textAlignment = NSTextAlignmentCenter;
            label.text = planNumberModels[i].nameString;
            label.font = [UIFont systemFontOfSize:10];
            
            // [self addSubview:label];
            // [self.view addSubview:label];
            [self.contentView addSubview:label];
            
            [label mas_makeConstraints:^(MASConstraintMaker * make) {
                make.centerX.mas_equalTo(titleLabel.mas_centerX).offset(0);
                make.top.mas_equalTo(titleLabel.mas_bottom).offset(0);
                make.width.mas_equalTo(45);
                make.height.mas_equalTo(15);
            }];
            label;
        });
        [self.bottomLabels addObject:bottomLabel];
        [self.labels addObject:titleLabel];
    }
    
    UIView * bgView = ({
        UIView * view = [[UIView alloc] init];
        
        view.backgroundColor = [UIColor whiteColor];
        //        view.layer.contents = (__bridge id _Nullable)([UIImage imageNamed:@"icon_bgimg"].CGImage);
        view.layer.contents = (__bridge id _Nullable)([UIImage imageNamed:@"bgbg"].CGImage);
        // [self addSubview:view];
        // [self.view addSubview:view];
        [self.contentView insertSubview:view atIndex:0];
        
        [view mas_makeConstraints:^(MASConstraintMaker * make) {
            make.left.mas_equalTo(self.contentView.mas_left).offset(12);
            make.right.mas_equalTo(self.contentView.mas_right).offset(-12);
            make.top.mas_equalTo(self.contentView.mas_top).offset(0);
            make.bottom.mas_equalTo(self.contentView.mas_bottom).offset(0);
        }];
        
        view.layer.cornerRadius = 4;
        view.layer.masksToBounds = YES;
        
        view;
    });
    self.bgView = bgView;
}
- (void)setupUI
{
    
}
- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    dispatch_async(dispatch_get_main_queue(), ^{
        self.iconImageView.layer.cornerRadius = self.iconImageView.bounds.size.width * 0.5;
        self.iconImageView.layer.masksToBounds = YES;
    });
}



@end
